import EditorTheme from './EditorTheme';

function getRacePromise(path, name) {
    return new Promise((resolve) => {
        fetch(path + name).then(o => {
            if (o.ok) { resolve([path, name]) }
        })
    })
}

function getLoaderPromise(path, name) {
    return new Promise((resolve, reject) => {
        let node = document.createElement('script');
        node.type = 'text/javascript';
        node.async = true;
        node.src = path + name;
        node.onload = () => resolve(path)
        node.onerror = () => reject()
        document.head.appendChild(node);
    })
}

async function getLoader() {
    let [path, name] = await Promise.race([
        getRacePromise('https://cdn.staticfile.org/monaco-editor/0.25.2/min/vs', '/loader.js'),
        getRacePromise('https://lib.baomitu.com/monaco-editor/0.25.2/min/vs', '/loader.min.js'),
        getRacePromise('https://cdn.bootcss.com/monaco-editor/0.25.2/min/vs', '/loader.min.js'),
        getRacePromise('https://cdn.jsdelivr.net/npm/monaco-editor@0.25.2/min/vs', '/loader.js'),
        getRacePromise('https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs', '/loader.js'),
        getRacePromise('https://unpkg.com/monaco-editor@0.25.2/min/vs', '/loader.js'),
        getRacePromise('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.25.2/min/vs', '/loader.min.js'),
    ])
    return getLoaderPromise(path, name)
}

let monacoPromise

/**
 * @returns {Promise<import('monaco-editor')>}
 */
async function getMonaco() {
    if (monacoPromise) return monacoPromise
    monacoPromise = new Promise((resolve) => {
        (async () => {
            let path = await getLoader()
            console.log('path', path);
            let require = window['require']
            require.config({ paths: { 'vs': path } });
            require(['vs/editor/editor.main'], () => {
                const monaco = window['monaco']
                EditorTheme.setUpLogTheme(monaco)
                EditorTheme.addTimeFormatProvider(monaco)
                resolve(monaco)
            })
        })()
    })
    return monacoPromise
}

export default {
    getMonaco
}